package com.feeling.xiu.ui

import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import com.feeling.xiu.R
import com.orhanobut.logger.Logger
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_register_second.*
import org.jetbrains.anko.support.v4.toast
import java.util.concurrent.TimeUnit


/**
 * A simple [Fragment] subclass.
 * Activities that contain this fragment must implement the
 * [RegisterSecondFragment.OnFragmentInteractionListener] interface
 * to handle interaction events.
 * Use the [RegisterSecondFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class RegisterSecondFragment : Fragment() {

    // TODO: Rename and change types of parameters
    private var mParam1: String? = null
    private var mParam2: String? = null
    var disposable: Disposable? = null

    private var mListener: OnFragmentInteractionListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null) {
            mParam1 = arguments.getString(ARG_PARAM1)
            mParam2 = arguments.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater!!.inflate(R.layout.fragment_register_second, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        progressView.setValue(0f);
//        iv_takeVideo.setOnClickListener(View.OnClickListener { progressView.value += 10 })
        iv_takeVideo.setOnTouchListener(button1Listener)


    }

    private val button1Listener = OnTouchListener({ arg0, event ->
        // TODO Auto-generated method stub
        val iAction = event.action
        if (iAction == MotionEvent.ACTION_DOWN) {   // 按下
            takeVideoAndUpProgress()
            return@OnTouchListener true
        } else if (iAction == MotionEvent.ACTION_UP) {  // 弹起
            progressView.value=0f
            disposable?.dispose()
        }
        false   // return false表示系统会继续处理
    })


    private fun takeVideoAndUpProgress() {

        progressView.setValue(5f);

        var observable = Observable
                .interval(1000, TimeUnit.MILLISECONDS)
                .repeat(4)

        var observer: Observer<Long> = object : Observer<Long> {
            override fun onSubscribe(d: Disposable?) {
                disposable = d

            }

            override fun onNext(t: Long?) {
                var currentPoint = t?.plus(1)
                Logger.e( "  currentPoint  : " + currentPoint)
                progressView.setValue(currentPoint!! * 25.toFloat());

                if (currentPoint!! >= 4) {
                    toast("录像完成了")
                    //todo 这儿进行一些网络操作 然后跳转
                    mListener!!.onFragmentInteraction(RegisterThirdFragment::class.java.simpleName)

                    disposable?.dispose()
                }

            }

            override fun onComplete() {
            }

            override fun onError(e: Throwable?) {
            }

        }
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer)


    }

    /*  // TODO: Rename method, update argument and hook method into UI event
      fun onButtonPressed(uri: Uri) {
          if (mListener != null) {
              mListener!!.onFragmentInteraction(uri)
          }
      }*/

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        if (context is OnFragmentInteractionListener) {
            mListener = context as OnFragmentInteractionListener?
        } else {
            throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener")
        }
    }

    override fun onDetach() {
        super.onDetach()
        mListener = null
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *
     *
     * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
     */
    interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        fun onFragmentInteraction(eventType: String)
    }

    companion object {
        // TODO: Rename parameter arguments, choose names that match
        // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
        private val ARG_PARAM1 = "param1"
        private val ARG_PARAM2 = "param2"

        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.

         * @param param1 Parameter 1.
         * *
         * @param param2 Parameter 2.
         * *
         * @return A new instance of fragment RegisterSecondFragment.
         */
        // TODO: Rename and change types and number of parameters
        fun newInstance(param1: String, param2: String): RegisterSecondFragment {
            val fragment = RegisterSecondFragment()
            val args = Bundle()
            args.putString(ARG_PARAM1, param1)
            args.putString(ARG_PARAM2, param2)
            fragment.arguments = args
            return fragment
        }
    }
}// Required empty public constructor
